package com.zmc.search.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.elasticsearch.common.xcontent.DeprecationHandler;

import java.util.Arrays;
import java.util.Objects;


/**
 * @Author：zmc
 * @Date：2024/11/29 9:45
 */
@Configuration
@ConfigurationProperties(prefix = "es")
@Slf4j
@Data
public class ElasticsearchConfig {

    private String hosts;
    private String username;
    private String password;
    private int connectTimeout;
    private int socketTimeout;
    private int connectionRequestTimeout;

    @Bean
    public RestHighLevelClient client() {
        HttpHost[] httpHosts = Arrays.stream(hosts.split(",")).map(host -> {
            String[] h = host.split(":");
            return new HttpHost(h[0], Integer.parseInt(h[1]));
        }).toArray(HttpHost[]::new);
        RestClientBuilder builder = RestClient.builder(httpHosts);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider))
                .setRequestConfigCallback(r -> {
                    r.setConnectTimeout(connectTimeout);
                    r.setSocketTimeout(socketTimeout);
                    r.setConnectionRequestTimeout(connectionRequestTimeout);
                    return r;
                });
        return new RestHighLevelClient(builder);
    }

}
